package com.study.juc.volatiles;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @program: juc-study
 * @author: jzhou
 * @date: 2022-08-16 10:51
 * @version: 1.0
 * @description: 双端锁发布案例（DCL）
 **/
public class SafeDoubleCheckLockSingleton {
	private static volatile SafeDoubleCheckLockSingleton singleton;
	private SafeDoubleCheckLockSingleton() { new AtomicInteger().getAndIncrement();	}



	//双重锁设计
	public static SafeDoubleCheckLockSingleton getInstance(){
		if (singleton == null){
			//1.多线程并发创建对象时，会通过加锁保证只有一个线程能创建对象
			synchronized(SafeDoubleCheckLockSingleton.class){
				if (singleton == null){
					//隐患：不加volatile，多线程环境下，由于重排序，该对象可能还未完成初始化就被其他线程读取
					singleton = new SafeDoubleCheckLockSingleton();
				}
			}
		}
		//2.对象创建完毕，执行getInstance()将不需要获取锁，直接返回创建对象
		return singleton;
	}

}
